﻿package cn.com.truelore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.ksoap2.serialization.SoapObject;

import cn.com.truelore.R;
import cn.com.truelore.adapter.TabContentPriceAdapter;
import cn.com.truelore.adapter.TabContentPriceDetailAdapter;
import cn.com.truelore.adapter.TabContentSettingStep1Adapter;
import cn.com.truelore.adapter.ViewHolderStetingStep1;
import cn.com.truelore.base.BaseActivity;
import cn.com.truelore.common.CommonAlertDialog;
import cn.com.truelore.common.Constants;
import cn.com.truelore.service.GfoWebService;
import cn.com.truelore.service.WebServiceThread;
import cn.com.truelore.vo.PriceVO;
import cn.com.truelore.vo.SettingStep1VO;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.style.SuperscriptSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 程序的主界面
 * 
 * @author Administrator
 * 
 */
public class TabContentPriceActivity extends BaseActivity {

	private int intCommodityType = 0;
	private int intOldNewType = Constants.TYPE_NEW;
	private int intSelectedIndex = 0;
	private String _cmids = null;
	private String _ctids = null;
	private String _strOntarioAlertPrice = null;
	private String _strChicagoAlertPrice = null;
	private List<PriceVO> listPriceVO = null;
	private List<Map<String, Object>> listDetails = null;

	ViewFlipper viewFlipperPrice = null;
	ListView listViewPriceView1 = null;
	private LinearLayout linearLayoutPriceMonth = null;
	private LinearLayout linearLayoutListViewHeader = null;
	TextView textViewMonth = null;
	LayoutInflater _layoutInflater = null;
	SharedPreferences COMMDNAMES = null;
	View viewListViewHeader = null;
	TabContentPriceAdapter _adapter = null;
	TabContentPriceDetailAdapter _adapterDetail = null;
	Handler _handlerWebService = null;
	ProgressDialog _progressDialog = null;
	/**
	 * Web Service
	 */
	private WebServiceThread _webServiceThread = null;

	public TabContentPriceActivity() {
		super(R.layout.tab_context_price);
	}

	public void initButtonClick() {
		Button btn = (Button) findViewById(R.id.btnPriceNew);
		btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				btnPriceNewCrop_OnClick(v);
			}
		});
		btn = (Button) findViewById(R.id.btnPriceOld);
		btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				btnPriceOldCrop_OnClick(v);
			}
		});

		ImageButton imgBtn = (ImageButton) findViewById(R.id.imgBtnPriceDetailAlertPrice);
		imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnPriceDetailAlertPrice_OnClick(v);
			}
		});

		imgBtn = (ImageButton) findViewById(R.id.imgBtnPriceDetailCallBroker);
		imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnPriceDetailCallBroker_OnClick(v);
			}
		});

		imgBtn = (ImageButton) findViewById(R.id.imgBtnAlertPriceSubmit);
		imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnAlertPriceSubmit_OnClick(v);
			}
		});

	}

	public void initPageData() {
		super.initPageData();
		intCommodityType = this.getIntent().getIntExtra("type", 0);
		viewFlipperPrice = (ViewFlipper) this
				.findViewById(R.id.viewFlipperPrice);
		textViewMonth = (TextView) findViewById(R.id.textViewMonth);
		listViewPriceView1 = (ListView) findViewById(R.id.listViewPriceView1);
		linearLayoutPriceMonth = (LinearLayout) findViewById(R.id.linearLayoutPriceMonth);
		linearLayoutListViewHeader = (LinearLayout) findViewById(R.id.linearLayoutListViewHeader);
		/*
		 * View headerView = super.getLayoutInflater().inflate(
		 * R.layout.listview_item_price_title, null);
		 * linearLayoutListViewHeader.addView(headerView);
		 */

		_layoutInflater = super.getLayoutInflater();
		listPriceVO = new ArrayList<PriceVO>();
		_adapter = new TabContentPriceAdapter(this);

		/*
		 * String strCommdType = super.getSharedPreferences(
		 * Constants.SP_TAB_NAMES, String.valueOf(intCommodityType));
		 */
		Button btn = (Button) findViewById(R.id.btnPriceNew);
		btn.setText("New Crop");
		btn = (Button) findViewById(R.id.btnPriceOld);
		btn.setText("Old Crop");
		// get alert price
		getSPAlertPrice();
		// list view data
		initListView();
	}

	private void getSPAlertPrice() {
		String key = Constants.ONT_PRICE + String.valueOf(intOldNewType)
				+ String.valueOf(intCommodityType);
		_strOntarioAlertPrice = super.getSharedPreferences(
				Constants.SP_ALERTPRICE, key);

		key = Constants.CCG_PRICE + String.valueOf(intOldNewType)
				+ String.valueOf(intCommodityType);
		_strChicagoAlertPrice = super.getSharedPreferences(
				Constants.SP_ALERTPRICE, key);
	}

	/**
	 * NewCrop click
	 * 
	 * @param v
	 */
	private void btnPriceNewCrop_OnClick(View v) {
		if (Constants.TYPE_NEW != intOldNewType) {
			intOldNewType = Constants.TYPE_NEW;
			setOldNewButtonBackColor();
			initListView();
		}

	}

	/**
	 * NewCrop click
	 * 
	 * @param v
	 */
	private void btnPriceOldCrop_OnClick(View v) {
		if (Constants.TYPE_OLD != intOldNewType) {
			intOldNewType = Constants.TYPE_OLD;
			setOldNewButtonBackColor();
			initListView();
		}
	}

	/**
	 * Alert Price
	 * 
	 * @param e
	 */
	private void imgBtnPriceDetailAlertPrice_OnClick(View v) {
		EditText editText = (EditText) findViewById(R.id.editTextAlertPriceOntario);
		editText.setText(_strOntarioAlertPrice);
		editText = (EditText) findViewById(R.id.editTextAlertPriceChicago);
		editText.setText(_strChicagoAlertPrice);
		viewFlipperPrice.showNext();
	}

	/**
	 * CallBroker
	 * 
	 * @param v
	 */
	private void imgBtnPriceDetailCallBroker_OnClick(View v) {
		String strPhone = super.getSharedPreferences(Constants.SP_SETTING,
				Constants.BROKERPHONE);
		if (StringUtils.isBlank(strPhone) == false) {
			Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
					+ strPhone));
			// 开始呼叫
			startActivity(intent);
		}
	}

	/**
	 * submit alert price
	 * 
	 * @param v
	 */
	private void imgBtnAlertPriceSubmit_OnClick(View v) {
		EditText editText = (EditText) findViewById(R.id.editTextAlertPriceOntario);
		_strOntarioAlertPrice = editText.getText().toString();
		String key = "";
		if (StringUtils.isBlank(_strOntarioAlertPrice) == false) {
			// price type + old new type + commodity type
			key = Constants.ONT_PRICE + String.valueOf(intOldNewType)
					+ String.valueOf(intCommodityType);
			super.setSharedPreferences(Constants.SP_ALERTPRICE, key,
					_strOntarioAlertPrice);
		}
		editText = (EditText) findViewById(R.id.editTextAlertPriceChicago);
		_strChicagoAlertPrice = editText.getText().toString();
		if (StringUtils.isBlank(_strChicagoAlertPrice) == false) {
			// price type + old new type + commodity type
			key = Constants.CCG_PRICE + String.valueOf(intOldNewType)
					+ String.valueOf(intCommodityType);
			super.setSharedPreferences(Constants.SP_ALERTPRICE, key,
					_strChicagoAlertPrice);
		}

		if (listPriceVO != null) {
			for (PriceVO priceVO : listPriceVO) {
				if (Constants.TYPE_CHICAGO == priceVO.getType()
						|| Constants.TYPE_MIN == priceVO.getType()) {
					priceVO.setAlertPrice(_strChicagoAlertPrice);
				} else {
					priceVO.setAlertPrice(_strOntarioAlertPrice);
				}
			}
			// 重新加载列表
			initPriceDetailList();
		}

		viewFlipperPrice.showPrevious();
	}

	/**
	 * 初始化ListView1
	 */
	private void initListView() {
		try {
			// 城市列表
			_ctids = super.getSharedPreferences(Constants.SP_SETTING,
					Constants.SP_SETTING_STEP2);
			// 类型
			if (Constants.TYPE_CORN == intCommodityType) {
				if (Constants.TYPE_OLD == intOldNewType) {
					_cmids = "1";
				} else {
					_cmids = "2";
				}
				initCornAndSoyListData();
			} else if (Constants.TYPE_SOY == intCommodityType) {
				if (Constants.TYPE_OLD == intOldNewType) {
					_cmids = "11";
				} else {
					_cmids = "12";
				}
				initCornAndSoyListData();
			} else if (Constants.TYPE_WHEAT == intCommodityType) {
				_cmids = super.getSharedPreferences(Constants.SP_SETTING,
						Constants.SP_SETTING_STEP3);
				initWheatListData();
			}
			if (StringUtils.isBlank(_cmids) == false
					&& StringUtils.isBlank(_ctids) == false) {
				_progressDialog = ProgressDialog.show(
						TabContentPriceActivity.this, super.getResources()
								.getString(R.string.app_name), super
								.getResources().getString(R.string.loading),
						true);
				try {
					_webServiceThread = new WebServiceThread(
							_handlerWebService, Constants.OP_CELEVLIST,
							new String[] { "cmids", "type", "ctids" },
							new String[] { _cmids,
									String.valueOf(intOldNewType), _ctids },
							new String[] { "CmID", "DT", "ENm", "F", "B", "C",
									"DS", "DE", "UD", "Chg", "DR" });

					_webServiceThread.doStart();
				} catch (Exception ex) {
					_progressDialog.dismiss();
				}
			}

		} catch (Exception ex) {
			Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	private void initCornAndSoyListData() {
		listPriceVO = new ArrayList<PriceVO>();
		listViewPriceView1.setAdapter(null);
		linearLayoutPriceMonth.setVisibility(8);
		linearLayoutListViewHeader.setVisibility(8);
		_handlerWebService = new Handler() {
			public void handleMessage(Message message) {

				Bundle bundler = message.getData();
				if (bundler == null
						|| StringUtils.isBlank(bundler.getString("error")) == false) {
					showErrorNetWork();
					return;
				}
				String strDT = "";
				if (bundler != null && bundler.size() > 0) {
					ArrayList<String> strArrayList = null;
					PriceVO addVO = null;
					for (int i = 0; i < bundler.size(); i++) {
						strArrayList = bundler.getStringArrayList(String
								.valueOf(i));
						addVO = new PriceVO(strArrayList);
						if (i == 0) {
							PriceVO priceVOChicago = new PriceVO();
							priceVOChicago.setCmID(addVO.getCmID());
							priceVOChicago.setDT(addVO.getDT());
							priceVOChicago.setENm(Constants.CHICAGO);
							priceVOChicago.setUD(addVO.getUD());
							priceVOChicago.setDR(addVO.getDR());
							priceVOChicago.setType(Constants.TYPE_CHICAGO);
							priceVOChicago.setF(addVO.getF());
							priceVOChicago.setB(Constants.CHAR_H);
							priceVOChicago.setC(Constants.CHAR_H);
							priceVOChicago.setAlertPrice(_strChicagoAlertPrice);
							strDT = addVO.getDT();
							listPriceVO.add(priceVOChicago);
						}
						addVO.setAlertPrice(_strOntarioAlertPrice);
						listPriceVO.add(addVO);
					}
				}
				if (listPriceVO.size() > 0) {
					linearLayoutPriceMonth.setVisibility(0);
					linearLayoutListViewHeader.setVisibility(0);
					textViewMonth.setText(strDT);
				}
				_adapter.setDataList(listPriceVO);
				listViewPriceView1.setAdapter(_adapter);
				listViewPriceView1.setItemsCanFocus(false);
				listViewPriceView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				listViewPriceView1
						.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// 触发事件处理
								listViewPriceView1_onItemClick(parent, view,
										position, id);
							}
						});

				_progressDialog.cancel();
				_progressDialog.dismiss();
			}
		};
	}

	private void initWheatListData() {
		COMMDNAMES = getSharedPreferences(Constants.SP_COMMDNAMES, 0);
		listPriceVO = new ArrayList<PriceVO>();
		listViewPriceView1.setAdapter(null);
		linearLayoutPriceMonth.setVisibility(8);
		linearLayoutListViewHeader.setVisibility(8);
		_handlerWebService = new Handler() {
			public void handleMessage(Message message) {
				Bundle bundler = message.getData();
				if (bundler == null
						|| StringUtils.isBlank(bundler.getString("error")) == false) {
					showErrorNetWork();
					return;
				}
				ArrayList<String> strArrayList = null;
				PriceVO addVO = null;
				String strCmId = "";
				for (int i = 0; i < bundler.size(); i++) {
					strArrayList = bundler
							.getStringArrayList(String.valueOf(i));
					addVO = new PriceVO(strArrayList);
					if (strCmId.equals(addVO.getCmID()) == false) {
						PriceVO titleVO = new PriceVO();
						strCmId = addVO.getCmID();
						titleVO.setENm(addVO.getDT() + " "
								+ COMMDNAMES.getString(strCmId, ""));
						titleVO.setType(Constants.TYPE_CMD_TITLE);
						listPriceVO.add(titleVO);

						PriceVO priceVOChicago = new PriceVO();
						priceVOChicago.setCmID(addVO.getCmID());
						priceVOChicago.setDT(addVO.getDT());
						if ("9".equals(addVO.getCmID()) == true
								|| "10".equals(addVO.getCmID()) == true) {
							priceVOChicago.setENm(Constants.MINNEAPOLIS);
							priceVOChicago.setType(Constants.TYPE_MIN);
						} else {
							priceVOChicago.setENm(Constants.CHICAGO);
							priceVOChicago.setType(Constants.TYPE_CHICAGO);
							priceVOChicago.setAlertPrice(_strChicagoAlertPrice);
						}
						priceVOChicago.setB(Constants.CHAR_H);
						priceVOChicago.setC(Constants.CHAR_H);
						priceVOChicago.setUD(addVO.getUD());
						priceVOChicago.setDR(addVO.getDR());
						priceVOChicago.setF(addVO.getF());
						listPriceVO.add(priceVOChicago);
					}
					addVO.setAlertPrice(_strOntarioAlertPrice);
					listPriceVO.add(addVO);
				}
				if (listPriceVO.size() > 0) {
					linearLayoutListViewHeader.setVisibility(0);
				}
				_adapter.setDataList(listPriceVO);
				listViewPriceView1.setAdapter(_adapter);
				listViewPriceView1.setItemsCanFocus(false);
				listViewPriceView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				listViewPriceView1
						.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// 触发事件处理
								listViewPriceView1_onItemClick(parent, view,
										position, id);
							}
						});

				_progressDialog.cancel();
				_progressDialog.dismiss();
			}
		};
	}

	private void showErrorNetWork() {
		_progressDialog.cancel();
		_progressDialog.dismiss();
		showAlertInfo(this.getResources().getString(R.string.errornetwork),true);
	}

	/**
	 * 点击事件
	 */
	private void listViewPriceView1_onItemClick(AdapterView<?> parent,
			View view, int position, long id) {
		if (listPriceVO != null && listPriceVO.size() >= position) {
			intSelectedIndex = position;
			PriceVO priceVO = listPriceVO.get(intSelectedIndex);
			if (Constants.TYPE_CMD_TITLE != priceVO.getType()) {
				initPriceDetailList();
				/*
				 * textViewTitle.setText(strType + " " + strCommdType + " " +
				 * priceVO.getENm());
				 */
				viewFlipperPrice.showNext();
			}
		}
	}

	private void initPriceDetailList() {
		String strCommdType = "";
		PriceVO priceVO = listPriceVO.get(intSelectedIndex);
		// 选择的是数据行
		if (Constants.TYPE_CMD_TITLE != priceVO.getType()) {
			strCommdType = super.getSharedPreferences(Constants.SP_COMMDNAMES,
					priceVO.getCmID());
			listDetails = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("title", Constants.DELIVERYSTART);
			map.put("context", priceVO.getDS());
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.DELIVERYEND);
			map.put("context", priceVO.getDE());
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.FUTURESPRICE);
			map.put("context", priceVO.getF());
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.BASIS);
			map.put("context", priceVO.getB());
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.CASHPRICE);
			if (StringUtils.isBlank(priceVO.getC()) == true
					|| Constants.CHAR_H.equals(priceVO.getC()) == true) {
				map.put("context", priceVO.getC());
			} else {
				String strDollar = this.getApplicationContext().getResources()
						.getString(R.string.dollar);
				map.put("context", strDollar + priceVO.getC());
			}
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.NOTES);
			map.put("context", priceVO.getDT() + " " + strCommdType);
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", Constants.ALERTPRICE);
			if (StringUtils.isBlank(priceVO.getAlertPrice()) == true) {
				map.put("context", "");
			} else {
				map.put("context",
						this.getApplicationContext().getString(R.string.dollar)
								+ priceVO.getAlertPrice());
			}
			listDetails.add(map);
			map = new HashMap<String, Object>();
			map.put("title", "Last Updated");
			map.put("context", priceVO.getUD());
			listDetails.add(map);

			// 设置标题
			TextView textViewTitle = (TextView) findViewById(R.id.textViewPriceView2Id1);
			textViewTitle.setText(priceVO.getENm());

			_adapterDetail = new TabContentPriceDetailAdapter(this);
			ListView listViewDetails = (ListView) findViewById(R.id.listViewPriceView2Detail);
			_adapterDetail.setDataList(listDetails);
			listViewDetails.setAdapter(_adapterDetail);
			listViewDetails.setItemsCanFocus(false);
			listViewDetails.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			/*
			 * listViewDetails.setOnItemClickListener(new OnItemClickListener()
			 * { public void onItemClick(AdapterView<?> parent, View view, int
			 * position, long id) { } });
			 */
		}
	}

	private void setOldNewButtonBackColor() {
		Button btn = null;
		if (Constants.TYPE_NEW == intOldNewType) {
			btn = (Button) findViewById(R.id.btnPriceNew);
			btn.setBackgroundResource(R.drawable.button_bg_on);
			btn = (Button) findViewById(R.id.btnPriceOld);
			btn.setBackgroundResource(R.drawable.button_bg_off);
		} else {
			btn = (Button) findViewById(R.id.btnPriceOld);
			btn.setBackgroundResource(R.drawable.button_bg_on);
			btn = (Button) findViewById(R.id.btnPriceNew);
			btn.setBackgroundResource(R.drawable.button_bg_off);
		}
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
				&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			viewFlipperPrice.showNext();
		} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
				&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			viewFlipperPrice.showPrevious();
		}
		if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
				&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			viewFlipperPrice.showNext();
		} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
				&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			viewFlipperPrice.showPrevious();
		}
		return false;
	}

	/**
	 * on key down
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (R.id.linearLayoutPriceView1 != viewFlipperPrice
					.getCurrentView().getId()) {
				viewFlipperPrice.showPrevious();
				return true;
			}
		}
		return false;
	}

}
